package yxy.game.pm2.bean.module.rank;

import org.redisson.api.RScoredSortedSet;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.module.BaseGameRedisBean;

import java.util.ArrayList;
import java.util.Collection;

public class RankWorship extends BaseGameRedisBean {

	private String key;
	private String rankName;

	public RankWorship(String rankKey, String rankName) {
		key = String.format("%s:WORSHIP", rankKey);
		this.rankName = rankName;
	}

	public ArrayList<String>  rankNames(){
		ArrayList<String>  rankNames = new ArrayList<>();
		rankNames.add("");
		return rankNames;
	}

	public String getRankName() {
		return rankName;
	}

	// func==========================================================================

	/** 膜拜 */
	public long worship(String code) {
		return addScore(code);
	}

	// redis==========================================================================

	private RScoredSortedSet<String> touch() {
		try {
			return RedisManager.client(redis()).getScoredSortedSet(key);
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return null;
	}

	private long addScore(String key) {
		try {
			if (tryLock()) {
				RScoredSortedSet<String> zset = touch();
				Double result = zset.addScore(key, 1);
				return result.longValue();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			unlock();
		}
		return 0;
	}

	public long getScore(String key) {
		try {
			RScoredSortedSet<String> zset = touch();
			Double result = zset.getScore(key);
			return result.longValue();
		} catch (Exception e) {
		}
		return 0;
	}

	public void remove(String key) {
		try {
			if (tryLock()) {
				RScoredSortedSet<String> zset = touch();
				zset.remove(key);
			}
		} catch (Exception e) {
		} finally {
			unlock();
		}
	}

	public void removeAll(Collection<String> keys) {
		try {
			if (tryLock()) {
				RScoredSortedSet<String> zset = touch();
				zset.removeAll(keys);
			}
		} catch (Exception e) {
		} finally {
			unlock();
		}
	}

	@Override
	public String lockKey() {
		return String.format("lock:%s", key);
	}

}
